package com.hellobike.haxing.web.cms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hellobike.haxing.anno.NoAuth;
import com.hellobike.haxing.operate.api.IOperateCmsPageService;
import com.hellobike.haxing.operate.model.vo.OperateCmsPageVo;
import com.hellobike.haxing.order.api.IOrderService;
import com.hellobike.haxing.order.result.Result;
import com.hellobike.haxing.product.api.ICouponService;
import com.hellobike.haxing.product.model.vo.CouponVo;
import com.hellobike.haxing.request.cms.CMSRequest;
import com.hellobike.haxing.response.cms.CMS;
import com.hellobike.haxing.response.cms.CMSImage;
import com.hellobike.haxing.response.cms.CMSResponse;
import com.hellobike.haxing.search.api.ProductSearchApi;
import com.hellobike.haxing.search.response.PageRespones;
import com.hellobike.haxing.search.vo.SearchProductParam;
import com.hellobike.haxing.search.vo.SearchProductVo;
import com.hellobike.haxing.user.vo.UserVo;
import com.hellobike.haxing.util.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/cms")
@Api(tags = "cms页面")
@NoAuth
@Slf4j
public class CMSController {

    @Reference(version = "1.0.0", check = true)
    private ICouponService couponService;

    @Reference(version = "1.0.0", check = true)
    private IOperateCmsPageService cmsPageService;

    @Reference(version = "1.0.0", check = true)
    private IOrderService orderService;

    @Reference(version = "1.0.0", check = true)
    private ProductSearchApi productSearchApi;

    @Autowired
    private UserUtil userUtil;

    @RequestMapping(value = "/list", method = {RequestMethod.POST})
    @ApiOperation("cms详情")
    @NoAuth
    public Result<CMSResponse> list(@RequestBody CMSRequest request) {
        log.info("赚钱攻略参数 ：{}", JSON.toJSONString(request));
        Result<CMSResponse> result = new Result<>();
        OperateCmsPageVo cmsPageVo = cmsPageService.queryCmsPage(request.getId());
        if (cmsPageVo == null || cmsPageVo.getStatus() == 2 || CollectionUtils.isEmpty(cmsPageVo.getComponents())) {
            result.faild(404, "页面不存在");
            return result;
        }
        UserVo userVo = userUtil.getUser();

        CMSResponse cmsResponse = new CMSResponse();
        cmsResponse.setPageBgColor(cmsPageVo.getPageBgColor());
        cmsResponse.setPageDesc(cmsPageVo.getPageDesc());
        cmsResponse.setPageName(cmsPageVo.getPageName());
        cmsResponse.setPageTitle(cmsPageVo.getPageTitle());
        cmsResponse.setComponents(new ArrayList<>());
        cmsResponse.setMainImage(cmsPageVo.getSharePicUrl());
        cmsPageVo.getComponents().forEach(vo -> {
            CMS cms = new CMS();
            cmsResponse.getComponents().add(cms);
            cms.setComponentStyle(vo.getComponentStyle());
            cms.setComponentType(vo.getComponentType());
            if (cms.getComponentType().equals(1) && !StringUtils.isEmpty(vo.getComponentInfoJsonb())) {
                List<CMSImage> cmgList = new ArrayList<>();
                JSONArray jsonArray = JSON.parseArray(vo.getComponentInfoJsonb());
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    CMSImage cmsImage = new CMSImage();
                    cmsImage.setParamType(jsonObject.getIntValue("paramType"));
                    cmsImage.setPicHigh(jsonObject.getInteger("picHigh"));
                    cmsImage.setPicWidth(jsonObject.getInteger("picWidth"));
                    cmsImage.setPicUrl(jsonObject.getString("picUrl"));
                    cmsImage.setProductId(jsonObject.getLongValue("productId"));
                    cmsImage.setUrl(jsonObject.getString("url"));
                    cmgList.add(cmsImage);
                }
                cms.setImages(cmgList);
            } else if (cms.getComponentType().equals(2) && !StringUtils.isEmpty(vo.getComponentInfoJsonb())) {
                JSONArray jsonArray = JSON.parseArray(vo.getComponentInfoJsonb());
                List<Long> couponIdList = new ArrayList<>();
                for (int i = 0; i < jsonArray.size(); i++) {
                    couponIdList.add(jsonArray.getJSONObject(i).getLongValue("id"));
                }
                Boolean hasPaid = orderService.hasPaidOrder(userVo.getId());
                List<CouponVo> couponVos = couponService.queryCopon(couponIdList, userVo.getId(), userVo.getShopVo().getId(), hasPaid ? 2 : 1);
                cms.setCouponVos(couponVos);
            } else if (cms.getComponentType().equals(3) && !StringUtils.isEmpty(vo.getComponentInfoJsonb())) {
                JSONArray jsonArray = JSON.parseArray(vo.getComponentInfoJsonb());
                List<Long> productIdList = new ArrayList<>();
                for (int i = 0; i < jsonArray.size(); i++) {
                    productIdList.add(jsonArray.getJSONObject(i).getLongValue("id"));
                }
                SearchProductParam searchProductParam = new SearchProductParam();
                searchProductParam.setCurrPage(1);
                searchProductParam.setPageSize(productIdList.size());
                searchProductParam.setProductIdList(productIdList);
                searchProductParam.setShopId(userVo.getShopVo().getId());
                PageRespones<SearchProductVo> pageRespones = productSearchApi.searchProduct(searchProductParam);
                Map<Long, SearchProductVo> productVoMap = pageRespones.getData().stream().collect(Collectors.toMap(SearchProductVo::getId, v -> v));
                List<SearchProductVo> searchProductVos = new ArrayList<>();
                productIdList.forEach(id -> {
                    SearchProductVo searchProductVo = productVoMap.get(id);
                    if (searchProductVo != null) {
                        searchProductVos.add(searchProductVo);
                    }
                });
                cms.setProductVos(searchProductVos);
            }
        });
        result.setData(cmsResponse);
        return result.success("");
    }
}
